<template>
  <view class="container_camera">
    <!-- <view @click="btn_back()"
          class="btn_back"
          :style="btnBackStyle">
      返回
    </view> -->

    <camera mode="normal"
            :device-position="backCamera ? 'back' : 'front'"
            :flash="flashing ? 'torch' : 'off'">
    </camera>

    <!-- 左侧预览列 -->
    <scroll-view :scroll-y="true"
                 :scroll-top="scrollTop"
                 class="container_preview">

      <view class="card_img"
            v-for="img,i in completeIMGs"
            :key="i">

        <text>{{  i + 1  }}</text>
        <uni-icons type="trash-filled"
                   color="red"
                   class="btn_del"
                   size="30"
                   @click="btn_delImg(i)" />

        <image mode="widthFix"
               :src="img" />
      </view>
    </scroll-view>

    <!-- 底部操作 -->
    <view class="container_control"
          :style="paddingBottom">
      <view @click="btn_openFlash()">
        {{ flashing ? '关闭闪光灯' : '打开闪关灯' }}
      </view>
      <!-- 当且仅当步骤为准备时 才显示开始检测 -->
      <view @click="btn_takePhoto()">
        {{ catching ? '请稍后' : '拍照' }}
      </view>

      <!-- 切换摄像头 -->
      <view @click="btn_flip()">
        切换摄像头
      </view>
    </view>
  </view>
</template>
<script>
import { baseImgUrl } from '@/config.js';
export default {
  props: ['limit', 'value'],
  data () {
    return {
      baseImgUrl: baseImgUrl, // 照片链接前缀 后端
      backCamera: true, // 当前是否为后置摄像头
      flashing: false, // 闪光灯已打开
      cameraContext: null, // 相机实例
      catching: false, // 正在拍摄中
      completeIMGs: [],
      scrollTop: 150,
      statusBarHeight: 0
    }
  },
  mounted () {
    if (uni.createCameraContext) {
      this.cameraContext = uni.createCameraContext()
      this.completeIMGs = this.value
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      uni.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  methods: {
    // 拍照
    btn_takePhoto () {
      if ((!this.catching && this.limit && this.completeIMGs.length < this.limit) || this.limit == null) {
        let beenAutoClosed = false // 用于判断闪关灯是否在这里被自动关闭了，因为安卓机拍的时候闪光灯被关掉了，要切换一次才能
        this.catching = true

        this.cameraContext.takePhoto({
          quality: 'normal',
          success: (res) => {
            // 成功后向照片中插入临时路径。
            this.completeIMGs.push(res.tempImagePath)
            this.scrollTop = this.completeIMGs.length * 300
            // console.log(res.tempImagePath)
            if (this.flashing) {
              beenAutoClosed = true
              this.flashing = false
            }
          },
          fail: (err) => {
            uni.showToast({
              title: '检测失败，请检查系统是否给予摄像头相关权限。',
              icon: 'none',
              duration: 1200
            })
          },
          complete: () => {
            let timer = setTimeout(() => {
              this.catching = false
              if (beenAutoClosed) this.flashing = true
              clearTimeout(timer)
            }, 500);
          }
        })
      } else if (this.limit && this.completeIMGs >= this.limit) {
        uni.showToast({
          title: '拍摄已达上限',
          icon: 'none',
          duration: 1200
        })
      }
    },

    // 删除
    btn_delImg (index) {
      this.completeIMGs.splice(index, 1)
    },

    // 切换摄像头
    btn_flip () {
      this.backCamera = !this.backCamera
      if (!this.backCamera) this.flashing = false
    },

    // 开启闪光灯
    btn_openFlash () {
      this.flashing = !this.flashing
    },

    // 返回
    btn_back () {

    },

    // 完成拍照
    btn_complete () {

    }
  },
  computed: {
    // 底部导航栏高度 单位px
    navigationBarHeight () {
      return uni.getStorageSync("menuInfo").navigationBarHeight || uni.getStorageSync("menuInfo").statusBarHeight / 2;
    },
    // 底部菜单padding掉导航栏的位置
    paddingBottom () {
      if (this.navigationBarHeight) {
        return `padding-bottom:${this.navigationBarHeight}px;`
      }
      else {
        return "";
      }
    },
    // // 左上角返回按钮
    // btnBackStyle () {
    //   const { menuTop, menuHeight } = uni.getStorageSync("menuInfo")
    //   return `height:${menuHeight}px;line-height:${menuHeight - 2}px;top:${menuTop}px;`
    // }
  },
  beforeDestroy () {
    this.$emit('input', this.completeIMGs)
  }
}
</script>
<style lang="scss" scoped>
.container_camera {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  z-index: 1;
  camera {
    height: 88vh;
  }
  .btn_back {
    position: absolute;
    z-index: 2;
    color: white;
    background: rgba(0, 0, 0, 0.3);
    width: 4em;
    text-align: center;
    border-radius: 2em;
    box-sizing: border-box;
    left: 12px;
    border: 1px solid #999;
  }

  .container_preview {
    position: absolute;
    z-index: 2;
    height: 60vh;
    top: 20vh;
    left: 12px;
    width: 100px;
    overflow: hidden auto;
    .btn_del {
      right: 0;
      position: absolute;
      z-index: 2;
    }
    .card_img {
      position: relative;
      margin-bottom: 12px;
      text {
        position: absolute;
        color: white;
        font-size: 20px;
        left: 6px;
        z-index: 2;
      }
      image {
        box-shadow: 0 0 20px;
        width: 100px;
      }
    }
  }

  .container_control {
    height: 12vh;
    width: 100%;
    background-color: #000;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    color: white;
    font-size: 18px;
    text-align: center;
    view {
      width: 30%;
    }
  }
}
</style>